<template>
  <div class="course-assessment">
    <h2>考核方式和课程评定</h2>
    <CourseChoose 
      :courseInfo="courseInfo || null" 
      :autoQueryParams="autoQueryParams"
      @course-selected="onCourseSelected" 
    />
    <div v-if="selectedCourse" class="assessment-section">
      <h3>考核方式设置</h3>
      
      <!-- 成绩占比设置 -->
      <div class="percentage-section">
        <h4>成绩占比设置</h4>
        <div class="percentage-row">
          <label>期末成绩占比：</label>
          <input v-model.number="finalPercentage" type="number" min="0" max="100" step="0.1" placeholder="请输入占比" />
          <span>%</span>
          <label style="margin-left: 20px;">平时成绩占比：</label>
          <input v-model.number="usualPercentage" type="number" min="0" max="100" step="0.1" placeholder="请输入占比" />
          <span>%</span>
        </div>
        <div class="percentage-total">
          总占比：{{ totalPercentage }}%
          <span v-if="totalPercentage !== 100" style="color: red;">（总占比应等于100%）</span>
        </div>
      </div>

      <!-- 评定说明 -->
      <div class="description-section">
        <h4>评定说明</h4>
        <div class="form-row">
          <label>平时成绩评定说明：</label>
          <textarea v-model="usualDesc" rows="4" placeholder="请输入平时成绩评定说明，支持换行"></textarea>
        </div>
        <div class="form-row">
          <label>期末成绩评定说明：</label>
          <textarea v-model="finalDesc" rows="4" placeholder="请输入期末成绩评定说明，支持换行"></textarea>
        </div>
      </div>

      <!-- 考核方式 -->
      <div class="method-section">
        <h4>考核方式</h4>
        <div v-if="courseGoals.length === 0" style="color: orange; margin-bottom: 10px;">
          提示：当前课程暂无课程目标数据，请先设置课程目标
        </div>

        <div v-for="(method, methodIndex) in assessmentMethods" :key="method.id" class="method-item">
          <div class="method-header">
            <span>考核方式 {{ methodIndex + 1 }}</span>
            <button @click="removeMethod(methodIndex)" class="delete-btn">删除</button>
          </div>
          
          <div class="method-content">
            <div class="form-row">
              <label>考核方式名称：</label>
              <input v-model="method.name" placeholder="请输入考核方式名称" />
            </div>
            <div class="form-row">
              <label>备注：</label>
              <input v-model="method.remark" placeholder="请输入备注（可选）" />
            </div>
            
            <!-- 课程目标列表 -->
            <div class="course-goals-section">
              <label>课程目标考核内容及占比：</label>
              
              <div class="course-goals-list">
                <div v-for="(courseGoal, goalIndex) in method.course_goal" :key="goalIndex" class="course-goal-item">
                  <div class="goal-header">
                    <span>课程目标 {{ goalIndex + 1 }}</span>
                    <button @click="removeCourseGoal(methodIndex, goalIndex)" class="delete-btn small">删除</button>
                  </div>
                  
                  <div class="goal-content">
                    <div class="form-row">
                      <label>目标：</label>
                      <select v-model="courseGoal.goal" @change="onGoalChange(methodIndex, goalIndex)">
                        <option value="">请选择课程目标</option>
                        <option v-for="goal in courseGoals" :key="goal.id" :value="goal.text">
                          {{ goal.text }}
                        </option>
                      </select>
                    </div>
                    <div class="form-row">
                      <label>目标比重：</label>
                      <input v-model.number="courseGoal.goalWeights" type="number" min="0" max="100" step="0.1" placeholder="0-100" style="width:100px;" />
                      <span>%</span>
                    </div>
                    <div class="form-row" v-if="courseGoal.goalWeights > 0">
                      <label>考核内容：</label>
                      <input v-model="courseGoal.exam_content" placeholder="请输入考核内容" maxlength="100" />
                    </div>
                  </div>
                </div>
              </div>
              
              <button @click="addCourseGoal(methodIndex)" class="add-btn small">添加课程目标</button>
              
              <div class="goal-weights-total">
                总占比：{{ getMethodGoalWeightsTotal(method.course_goal) }}%
                <span v-if="getMethodGoalWeightsTotal(method.course_goal) !== 100" style="color: red;">（总占比应等于100%）</span>
              </div>
            </div>
          </div>
        </div>
        
        <button @click="addMethod" class="add-btn">添加考核方式</button>
      </div>

      <div class="save-section">
        <button @click="saveAssessment" class="save-btn">保存</button>
      </div>
    </div>
  </div>
</template>

<script>
import CourseChoose from './CourseChoose.vue';
import { courseApi } from '../api/index.js';

export default {
  name: 'CourseAssessment',
  components: { CourseChoose },
  props: {
    courseInfo: {
      type: Object,
      default: null
    },
    autoQueryParams: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      selectedCourse: null,
      finalPercentage: 60,
      usualPercentage: 40,
      usualDesc: '',
      finalDesc: '',
      assessmentMethods: [],
      courseGoals: [],
    };
  },
  computed: {
    totalPercentage() {
      return (this.finalPercentage || 0) + (this.usualPercentage || 0);
    },
    courseGoalsCount() {
      return this.courseGoals.length;
    },
  },
  watch: {
    // 监听props变化，如果有课程信息则自动选择
    courseInfo: {
      handler(newCourseInfo) {
        if (newCourseInfo && Object.keys(newCourseInfo).length > 0 && newCourseInfo.id) {
          this.onCourseSelected(newCourseInfo);
        } else {
          // 如果没有有效的课程信息，清空状态
          this.selectedCourse = null;
          this.resetForm();
        }
      },
      immediate: true
    }
  },
  methods: {
    async onCourseSelected(course) {
      this.selectedCourse = course;
      if (course && course.id) {
        // 先加载课程目标，再加载考核方式数据
        await this.loadCourseGoals();
        await this.loadAssessmentData();
      } else {
        this.resetForm();
      }
    },

    // 加载课程目标数据
    async loadCourseGoals() {
      if (!this.selectedCourse || !this.selectedCourse.id) {
        this.courseGoals = [];
        return;
      }
      
      try {
        const response = await courseApi.queryCourseGoals(this.selectedCourse.id);

        if (response && response.success === 0 && response.data) {
          // 将课程目标数据转换为组件需要的格式
          this.courseGoals = response.data.map((goal, index) => ({
            id: (index + 1).toString(),
            text: goal
          }));
          
          // 如果当前没有考核方式，自动添加一个空的考核方式
          if (this.assessmentMethods.length === 0) {
            this.addMethod();
          }
        } else {
          this.courseGoals = [];
        }
      } catch (error) {
        console.error('加载课程目标失败：', error);
        this.courseGoals = [];
      }
    },

    // 加载考核方式数据
    async loadAssessmentData() {
      if (!this.selectedCourse || !this.selectedCourse.id) {
        return;
      }

      try {
        const response = await courseApi.queryAssessment(this.selectedCourse.id);
        
        if (response && response.data) {
          // 填充表单数据
          this.finalPercentage = response.data.final_percentage || 60;
          this.usualPercentage = response.data.usual_percentage || 40;
          this.usualDesc = response.data.usual_desc || '';
          this.finalDesc = response.data.final_desc || '';
          
          // 处理考核方式数据
          if (response.data.method) {
            // 如果method是字符串，需要解析成数组格式
            this.assessmentMethods = this.parseMethodData(response.data.method);
          } else {
            this.assessmentMethods = [];
          }
          
          // 如果没有考核方式但有课程目标，自动添加一个空的考核方式
          if (this.assessmentMethods.length === 0 && this.courseGoals.length > 0) {
            this.addMethod();
          }
        }
      } catch (error) {
        console.error('加载考核方式数据失败：', error);
        // 如果查询失败，只重置考核方式相关数据，保留课程目标
        this.finalPercentage = 60;
        this.usualPercentage = 40;
        this.usualDesc = '';
        this.finalDesc = '';
        this.assessmentMethods = [];
        // 不清空 courseGoals，因为课程目标是通过其他接口查询的
      }
    },

    // 解析考核方式数据
    parseMethodData(methodData) {
      // 这里需要根据后端返回的数据格式进行解析
      // 假设method是一个JSON字符串或者已经是对象
      let parsedData = [];
      if (typeof methodData === 'string') {
        try {
          parsedData = JSON.parse(methodData);
        } catch (e) {
          console.error('解析考核方式数据失败：', e);
          return [];
        }
      } else {
        parsedData = methodData || [];
      }

      // 确保每个考核方式都有正确的数据结构
      return parsedData.map(method => {
        const updatedMethod = {
          id: method.id || Date.now() + Math.random(),
          name: method.name || '',
          remark: method.remark || '',
          course_goal: method.course_goal || []
        };
        
        // 确保每个课程目标都有正确的字段
        updatedMethod.course_goal = updatedMethod.course_goal.map(goal => ({
          goal: goal.goal || '',
          goalWeights: goal.goalWeights || 0,
          exam_content: goal.exam_content || ''
        }));
        
        // 如果没有课程目标，添加一个空的
        if (updatedMethod.course_goal.length === 0) {
          updatedMethod.course_goal.push({
            goal: '',
            goalWeights: 0,
            exam_content: ''
          });
        }
        
        return updatedMethod;
      });
    },

    // 重置表单
    resetForm() {
      this.finalPercentage = 60;
      this.usualPercentage = 40;
      this.usualDesc = '';
      this.finalDesc = '';
      this.assessmentMethods = [];
      this.courseGoals = [];
    },

    addMethod() {
      const newMethod = {
        id: Date.now() + Math.random(),
        name: '',
        remark: '',
        course_goal: []
      };
      this.assessmentMethods.push(newMethod);
      // 自动添加一个空的课程目标
      this.addCourseGoal(this.assessmentMethods.length - 1);
    },

    removeMethod(index) {
      this.assessmentMethods.splice(index, 1);
    },

    addCourseGoal(methodIndex) {
      const newCourseGoal = {
        goal: '',
        goalWeights: 0,
        exam_content: ''
      };
      this.assessmentMethods[methodIndex].course_goal.push(newCourseGoal);
    },

    removeCourseGoal(methodIndex, goalIndex) {
      this.assessmentMethods[methodIndex].course_goal.splice(goalIndex, 1);
    },

    onGoalChange(methodIndex, goalIndex) {
      // 当选择课程目标时，可以在这里添加额外的逻辑
      // console.log('课程目标选择变化:', methodIndex, goalIndex);
    },

    getMethodGoalWeightsTotal(courseGoals) {
      return courseGoals.reduce((sum, goal) => sum + (parseFloat(goal.goalWeights) || 0), 0).toFixed(1);
    },

    // 构建考核方式字符串
    buildMethodString() {
      return this.assessmentMethods.map(method => ({
        name: method.name,
        remark: method.remark,
        course_goal: method.course_goal
      }));
    },

    // 构建课程目标字符串
    buildCourseGoalString() {
      return this.assessmentMethods.map(method => 
        method.course_goal.map(goal => 
          goal.goalWeights > 0 && goal.goal ? `${goal.goal}(${goal.goalWeights}%)` : ''
        ).filter(text => text).join('; ')
      ).join(' | ');
    },

    // 构建考核内容字符串
    buildExamContentString() {
      return this.assessmentMethods.map(method => 
        method.course_goal.map(goal => 
          goal.goalWeights > 0 && goal.goal ? `${goal.goal}: ${goal.exam_content}` : ''
        ).filter(text => text).join('; ')
      ).join(' | ');
    },

    async saveAssessment() {
      if (!this.selectedCourse || !this.selectedCourse.id) {
        alert('请先选择课程');
        return;
      }

      // 验证数据
      if (this.totalPercentage !== 100) {
        alert('期末成绩占比和平时成绩占比之和应等于100%！');
        return;
      }

      for (let method of this.assessmentMethods) {
        // 检查是否有课程目标
        if (method.course_goal.length === 0) {
          alert('每个考核方式至少需要添加一个课程目标！');
          return;
        }
        
        // 检查课程目标占比总和
        const totalWeight = parseFloat(this.getMethodGoalWeightsTotal(method.course_goal));
        if (totalWeight !== 100) {
          alert(`考核方式"${method.name || '未命名'}"的课程目标占比之和应等于100%，当前为${totalWeight}%！`);
          return;
        }
        
        // 检查每个课程目标的完整性
        for (let goal of method.course_goal) {
          if (goal.goalWeights > 0 && !goal.exam_content) {
            alert('有占比大于0的课程目标，请填写对应的考核内容！');
            return;
          }
          if (goal.goalWeights > 0 && !goal.goal) {
            alert('有占比大于0的课程目标，请选择对应的课程目标！');
            return;
          }
        }
      }

      try {
        const params = {
          courseId: this.selectedCourse.id,
          method: JSON.stringify(this.buildMethodString()),
          course_goal: this.buildCourseGoalString(),
          exam_content: this.buildExamContentString(),
          remark: this.assessmentMethods.map(m => m.remark).join(' | '),
          usual_percentage: this.usualPercentage,
          final_percentage: this.finalPercentage,
          usual_desc: this.usualDesc,
          final_desc: this.finalDesc
        };

        const response = await courseApi.saveAssessment(params);
        
        if (response && response.success===0) {
          alert('保存成功！');
        } else {
          alert('保存失败：' + (response.message || '未知错误'));
        }
      } catch (error) {
        console.error('保存考核方式失败：', error);
        alert('保存失败，请重试');
      }
    },
  },
};
</script>

<style scoped>
.course-assessment {
  padding: 24px;
  color: #333; /* 设置默认文字颜色为深灰色 */
}

.course-assessment h2 {
  color: #333; /* 确保主标题颜色正常 */
}
.assessment-section {
  margin-top: 32px;
  border-top: 1px solid #eee;
  padding-top: 20px;
  max-width: 800px;
}

.assessment-section h3 {
  color: #333; /* 确保考核方式设置标题颜色正常 */
}

.assessment-section h4 {
  color: #333; /* 确保子标题颜色正常 */
}
.percentage-section,
.description-section,
.method-section {
  margin-bottom: 32px;
  padding: 16px;
  background: #f9f9f9;
  border-radius: 8px;
}
.percentage-row {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

.percentage-row label {
  color: #333; /* 确保占比设置标签颜色正常 */
}

.percentage-row span {
  color: #333; /* 确保占比符号颜色正常 */
}
.percentage-row input {
  width: 100px;
  padding: 4px 8px;
  color: #333; /* 确保输入框文字颜色正常 */
}
.percentage-total {
  font-weight: bold;
  margin-top: 8px;
  color: #333; /* 确保占比总计颜色正常 */
}
.form-row {
  display: flex;
  align-items: flex-start;
  margin-bottom: 16px;
  gap: 8px;
}
.form-row label {
  min-width: 140px;
  font-weight: 500;
  color: #333; /* 确保表单标签颜色正常 */
}
.form-row input,
.form-row textarea,
.form-row select {
  flex: 1;
  padding: 4px 8px;
  color: #333; /* 确保输入框文字颜色正常 */
}
.form-row textarea {
  resize: vertical;
}
.method-item {
  margin-bottom: 20px;
  padding: 16px;
  background: #fff;
  border-radius: 6px;
  border: 1px solid #ddd;
}
.method-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  font-weight: bold;
  color: #333; /* 确保方法头部文字颜色正常 */
}
.delete-btn {
  background: #ff4d4f;
  color: #fff;
  border: none;
  padding: 4px 12px;
  border-radius: 4px;
  cursor: pointer;
}
.delete-btn.small {
  padding: 2px 8px;
  font-size: 12px;
}
.course-goals-section {
  margin-top: 16px;
}
.course-goals-list {
  margin-bottom: 12px;
}
.course-goal-item {
  margin-bottom: 16px;
  padding: 12px;
  background: #f5f5f5;
  border-radius: 4px;
  border: 1px solid #e0e0e0;
}
.goal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
  font-weight: 500;
  font-size: 14px;
  color: #333; /* 确保目标头部文字颜色正常 */
}
.goal-content {
  padding-left: 8px;
}
.goal-content .form-row {
  margin-bottom: 8px;
}
.goal-content .form-row label {
  min-width: 80px;
  font-size: 13px;
  color: #333; /* 确保目标内容标签颜色正常 */
}
.goal-weights-total {
  margin-top: 8px;
  font-weight: bold;
  color: #333; /* 确保目标权重总计颜色正常 */
}
.add-btn {
  background: #409eff;
  color: #fff;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
}
.add-btn.small {
  padding: 4px 12px;
  font-size: 12px;
}
.save-btn {
  background: #409eff;
  color: #fff;
  border: none;
  padding: 10px 32px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
}
</style> 